<template>
  <t-form
    ref="form"
    :class="['item-container', `login-${type}`]"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <t-form-item name="password">
      <t-input
        v-model="formData.password"
        size="large"
        :type="showPsw ? 'text' : 'password'"
        clearable
        placeholder="请输入登录密码"
      >
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
        <template #suffix-icon>
          <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item name="password2">
      <t-input
        v-model="formData.password2"
        size="large"
        :type="showPsw ? 'text' : 'password'"
        clearable
        placeholder="请再次输入密码"
      >
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
        <template #suffix-icon>
          <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
        </template>
      </t-input>
    </t-form-item>

    <t-form-item v-if="type !== 'qrcode'" class="btn-container">
      <t-button block size="large" type="submit"> 确定修改 </t-button>
    </t-form-item>
  </t-form>
</template>

<script setup lang="ts">
import { ref } from 'vue';

import { FormInstanceFunctions, MessagePlugin } from 'tdesign-vue-next';
import { changeLoginPwd } from '@/api/member';
import { useUserStore } from '@/store';

const props = defineProps({
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});
const emit = defineEmits(['onClose']);
const userStore = useUserStore();

const INITIAL_DATA = {
  password: '',
  password2: '',
};

const FORM_RULES = {
  password: [{ required: true, message: '密码必填', type: 'error' }],
  password2: [{ required: true, message: '密码必填', type: 'error' }],
};

const type = ref('password');

const form = ref<FormInstanceFunctions>();
const formData = ref({ ...INITIAL_DATA });
const showPsw = ref(false);

const onSubmit = async ({ validateResult }) => {
  if (validateResult === true) {
    // 更换密码逻辑
    await changeLoginPwd({
      userId: props.data.userId,
      password: formData.value.password,
    })
      .then((ret) => {
        MessagePlugin.success('保存成功');
      })
      .catch((e) => {
        if (e.message) {
          MessagePlugin.error(e.message);
        } else {
          MessagePlugin.error(e.msg);
        }
      });
    formData.value = { ...INITIAL_DATA };
    emit('onClose');
  }
};
</script>

<style lang="less" scoped>
//@import url('./index.less');
</style>
